<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive } from 'vue'
import { accountLogin, sendEmailCode, emailLogin, saveToken, saveUserInfo, getDynamicRouterAsync } from '@/api'
import router, { addDynamicRoutes } from '@/router'

// 登录类型
type LoginType = 'password' | 'email'

// 响应式数据
const loginType = ref<LoginType>('password')
const loading = ref(false)

// 表单数据
const form = reactive({
  account: '',
  password: '',
  email: '',
  verificationCode: ''
})

// 验证码相关
const countdown = ref(0)
const canSendCode = ref(true)

// 切换登录方式
const switchLoginType = (type: LoginType) => {
  loginType.value = type
  // 清空表单
  Object.keys(form).forEach(key => {
    form[key as keyof typeof form] = ''
  })
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!form.email) {
    ElMessage.error('请输入邮箱地址')
    return
  }

  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) {
    ElMessage.error('请输入有效的邮箱地址')
    return
  }

  try {
    loading.value = true
    // 调用发送验证码 API
    const response = await sendEmailCode({ email: form.email })

    if (response.success) {
      // 开始倒计时
      countdown.value = 120
      canSendCode.value = false
      const timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
          canSendCode.value = true
        }
      }, 1000)
    } else {
      ElMessage.error(response.message)
    }


  } catch (error) {
    ElMessage.error('发送验证码失败，请重试' + error)
  } finally {
    loading.value = false
  }
}

// 登录
const handleLogin = async () => {
  if (loginType.value === 'password') {
    if (!form.account || !form.password) {
      ElMessage.error('请输入账号和密码')
      return
    }
  } else {
    if (!form.email || !form.verificationCode) {
      ElMessage.error('请输入邮箱和验证码')
      return
    }
  }

  try {
    loading.value = true
    let response

    if (loginType.value === 'password') {
      // 账号密码登录
      response = await accountLogin({
        account: form.account,
        password: form.password
      })
    } else {
      // 邮箱验证码登录
      response = await emailLogin({
        email: form.email,
        code: form.verificationCode
      })
    }
    // 保存 token 和用户信息
    if (response.success && response.data?.token) {
      saveToken(response.data.token)
      // 保存用户信息
      if (response.data.user) {
        saveUserInfo(response.data.user)
      }

      // 获取动态菜单并添加到路由
      try {
        // 假设用户ID为1，实际项目中应该从登录响应中获取
        const menuResponse = await getDynamicRouterAsync({ userId: 1 })
        if (menuResponse.success && menuResponse.data && Array.isArray(menuResponse.data)) {
          addDynamicRoutes(menuResponse.data)
        }
      } catch (menuError) {
        console.error('获取动态菜单失败:', menuError)
        // 即使菜单获取失败，也允许登录
      }

      ElMessage.success('登录成功！')
      // 跳转到主页
      router.push('/main')
    } else {
      ElMessage.error(response.message || '登录失败，请检查账号信息')
    }
  } catch (error) {
    ElMessage.error('登录失败，请重试' + error)
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h1>存储管理系统</h1>
        <p>Warehouse Management System</p>
      </div>

      <div class="login-tabs">
        <el-button :type="loginType === 'password' ? 'primary' : ''" @click="switchLoginType('password')"
          class="tab-button">
          账号密码登录
        </el-button>
        <el-button :type="loginType === 'email' ? 'primary' : ''" @click="switchLoginType('email')" class="tab-button">
          邮箱验证码登录
        </el-button>
      </div>

      <!-- 账号密码登录 -->
      <div v-if="loginType === 'password'" class="login-form">
        <el-form :model="form" label-width="0">
          <el-form-item>
            <el-input v-model="form.account" placeholder="请输入账号" size="large" prefix-icon="User" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="form.password" type="password" placeholder="请输入密码" size="large" prefix-icon="Lock"
              show-password @keyup.enter="handleLogin" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" :loading="loading" @click="handleLogin" class="login-button">
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="demo-account">
          <p>演示账号：admin / 123456</p>
        </div>
      </div>

      <!-- 邮箱验证码登录 -->
      <div v-else class="login-form">
        <el-form :model="form" label-width="0">
          <el-form-item>
            <el-input v-model="form.email" placeholder="请输入邮箱地址" size="large" prefix-icon="Message" />
          </el-form-item>
          <el-form-item>
            <div class="code-input-group">
              <el-input v-model="form.verificationCode" placeholder="请输入验证码" size="large" prefix-icon="Key"
                @keyup.enter="handleLogin" />
              <el-button :disabled="!canSendCode || !form.email" :loading="loading" @click="sendVerificationCode"
                class="send-code-btn">
                {{ canSendCode ? '发送验证码' : `${countdown}秒后重发` }}
              </el-button>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="large" :loading="loading" @click="handleLogin" class="login-button">
              {{ loading ? '登录中...' : '登录' }}
            </el-button>
          </el-form-item>
        </el-form>

        <div class="demo-account">
          <p>演示验证码：123456</p>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-box {
  background: white;
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h1 {
  color: #333;
  margin-bottom: 8px;
  font-size: 24px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.login-tabs {
  display: flex;
  margin-bottom: 24px;
  border-bottom: 1px solid #eee;
}

.tab-button {
  flex: 1;
  border: none;
  border-radius: 0;
  padding: 12px;
}

.login-form {
  margin-top: 20px;
}

.login-button {
  width: 100%;
  margin-top: 10px;
}

.code-input-group {
  display: flex;
  gap: 10px;
}

.send-code-btn {
  white-space: nowrap;
}

.demo-account {
  margin-top: 20px;
  padding: 12px;
  background: #f5f7fa;
  border-radius: 6px;
  text-align: center;
}

.demo-account p {
  margin: 0;
  color: #666;
  font-size: 12px;
}

:deep(.el-input__wrapper) {
  border-radius: 6px;
}

:deep(.el-button) {
  border-radius: 6px;
}
</style>
